<script>
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Search from "@iconify-icons/ep/search";
export default {
  name: "jobsTreeTransfer",

  components: {},
  props: {
    // 是否是多选
    isMulti: {
      type: Boolean,
      default: false
    },
    // 是否是人员选择组件
    isEmployee: {
      type: Boolean,
      default: false
    },
    // 是否是人员部门混合
    isMix: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      Search,
      openDialog: false,
      treeProps: {
        label: "label",
        children: "children"
      },
      allSearchValue: "",
      hasSearchValue: "",
      treeRef: null,
      hasSelectionList: [],
      rightUserList: [],
      treeData: [],
      // 记录单击高亮的node节点
      highlightMap: {},
      // 定义点击次数，默认为0
      treeClickCount: 0,
      activeBtn: "group",
      singleSelectNode: {},
      employeeList: [],
      addGroupVisiable: false,
      gruopForm: {
        gruopName: "",
        gruopers: []
      },
      gruopRules: {
        gruopName: [{ required: true, message: "请输入组名", trigger: "blur" }]
      },
      employeeActive: null,
      jobsList: [],
      jobActive: null
    };
  },

  methods: {
    useRenderIcon,
    onChangeVisible() {
      this.openDialog = true;
    },
    handleCheckChange(data, checked) {
      this.hasSelectionList = this.$refs.treeRef.getCheckedNodes(true);
      // console.log('勾选的数据：', hasSelectionList.value)
      this.rightUserList = this.hasSelectionList;
    },
    initAdd() {
      // this.openDialog = true
      //查询树的数据
      if (this.activeBtn === "group") {
        this.treeData = [
          {
            label: "中储智慧物流有限公司",
            id: "1",
            children: [
              {
                label: "前端组",
                id: "1-1",
                groupType: "公共组"
              },
              {
                label: "中层领导",
                id: "1-2",
                groupType: "公共组"
              },
              {
                label: "领导班子",
                id: "1-3",
                groupType: "私有组"
              }
            ]
          },
          {
            label: "金湖分公司",
            id: "2",
            children: [
              {
                label: "前端组",
                id: "1-1",
                groupType: "公共组"
              },
              {
                label: "中层领导",
                id: "1-2",
                groupType: "公共组"
              },
              {
                label: "领导班子",
                id: "1-3",
                groupType: "私有组"
              }
            ]
          },
          {
            label: "徐州分公司",
            id: "2",
            children: [
              {
                label: "前端组",
                id: "1-1",
                groupType: "公共组"
              },
              {
                label: "中层领导",
                id: "1-2",
                groupType: "公共组"
              },
              {
                label: "领导班子",
                id: "1-3",
                groupType: "私有组"
              }
            ]
          }
        ];
      } else if (this.activeBtn === "job") {
        this.jobsList = [
          {
            jobCode: "2112001",
            jobName: "书记",
            id: "001"
          },
          {
            jobCode: "2112002",
            jobName: "总裁",
            id: "002"
          },
          {
            jobCode: "2112003",
            jobName: "产品经理",
            id: "003"
          },
          {
            jobCode: "2112004",
            jobName: "总经理",
            id: "004"
          },
          {
            jobCode: "2112005",
            jobName: "总经理助理",
            id: "005"
          }
        ];
      } else {
        this.treeData = [
          {
            label: "中储智慧物流有限公司",
            id: "1",
            children: [
              {
                label: "工会",
                id: "1-1",
                groupType: "私有组"
              },
              {
                label: "技术中心",
                id: "1-2",
                groupType: "私有组",
                children: [
                  {
                    label: "测试部",
                    id: "1-2-1"
                  },
                  {
                    label: "产品部",
                    id: "1-2-2",
                    children: [
                      {
                        label: "前端开发组",
                        id: "1-2-2-1"
                      }
                    ]
                  }
                ]
              },
              {
                label: "运营部",
                id: "1-3",
                groupType: "私有组",
                children: [
                  {
                    label: "客服组",
                    id: "1-3-1"
                  },
                  {
                    label: "多式联运部",
                    id: "1-3-2",
                    children: [
                      {
                        label: "演示员2",
                        id: "1-3-2-1"
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ];
      }
    },
    confirmBind() {
      this.openDialog = false;
      this.$emit("submit");
    },
    handleClose() {
      this.allSearchValue = this.hasSearchValue = "";
      this.hasSelectionList = [];
      this.openDialog = false;
    },
    searchUser(type) {
      if (type === "left") {
        this.$refs.treeRef.filter(this.allSearchValue);
      } else {
        this.hasSelectionList = this.rightUserList.filter(e =>
          e.label.includes(this.hasSearchValue)
        );
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.includes(value);
    },
    removeUser(item, index) {
      //从集合中移出
      this.hasSelectionList.splice(index, 1);
      //重新设置勾选数据
      if (this.isMulti) {
        this.$refs.treeRef.setCheckedNodes(this.hasSelectionList);
      } else {
        this.rightUserList.splice(index, 1);
      }
      // 如果是人员组件，删除时要刷新左侧人员列表checkbox状态
      if (this.isEmployee) {
        this.employeeList.find(e => {
          if (e.id === item.id) {
            e.checked = false;
          }
        });
      }
    },
    // 自定义单双击事件
    handleNodeClick(data, node) {
      const nodeId = data.$treeNodeId;
      this.highlightMap[nodeId] = this.highlightMap[nodeId]?.highlight
        ? Object.assign({ id: nodeId }, this.highlightMap[nodeId], {
            highlight: false
          })
        : Object.assign({ id: nodeId }, this.highlightMap[nodeId], {
            highlight: true
          });
      Object.values(this.highlightMap).forEach(v => {
        if (v.id !== nodeId) {
          v.highlight = false;
        }
      });
      if (this.treeClickCount > 2) {
        return;
      }
      clearTimeout(this.clickTimer);
      this.clickTimer = setTimeout(() => {
        if (this.treeClickCount === 1) {
          // 先把计数器归零再做单击事件处理
          this.treeClickCount = 0;

          // 单选时点击中间箭头数据穿梭
          if ((!this.isMulti && !this.isEmployee) || this.isMix) {
            this.singleSelectNode = new Array(data);
          }
          if (
            this.isEmployee &&
            (!data.children || data.children.length === 0)
          ) {
            this.employeeList = this.queryEmployeeByNode().map(e => {
              return {
                ...e,
                checked: false
              };
            });
          }
        } else if (this.treeClickCount > 1) {
          // 双击事件
          this.treeClickCount = 0;
          // 单选时
          if (
            !this.isMulti &&
            this.hasSelectionList.length < 2 &&
            (!data.children || data.children.length === 0)
          ) {
            this.rightUserList = new Array(data);
            this.hasSelectionList = new Array(data);
          }
          // 部门和人员混选时
          if (this.isMix) {
            if (this.hasSelectionList.find(e => e.id === data.id)) {
              this.$message.warning("此员工已在右侧列表，请重新选择！");
              return;
            }
            this.rightUserList.push(data);
            this.hasSelectionList.push(data);
          }
        }
      }, 300);
      this.treeClickCount++;
    },

    // 顶部切换树数据
    switchTreeData(type) {
      this.activeBtn = type;
      this.initAdd();
    },

    // 左箭头，数据删除
    handleLeftArrow() {},

    // 右箭头，数据增加
    handleRightArrow() {
      if (this.singleSelectNode && this.singleSelectNode.length !== 0) {
        // 单选时替换
        if (!this.isMulti) {
          this.rightUserList = this.singleSelectNode;
          this.hasSelectionList = this.singleSelectNode;
        }
        // 人员和部门混选时追加
        if (this.isMix) {
          // 右箭头增加时，所选项只会有一个，singleSelectNode.length一直为1
          if (
            this.hasSelectionList.find(
              e => e.id === this.singleSelectNode[0].id
            )
          ) {
            this.$message.warning("此员工已在右侧列表，请重新选择！");
            return;
          }
          this.rightUserList.push(this.singleSelectNode[0]);
          this.hasSelectionList.push(this.singleSelectNode[0]);
        }
      }
    },

    queryEmployeeByNode(id) {
      const employeeList = [
        {
          employeeName: "张三",
          id: "1812021",
          levelName: "产品经理1"
        },
        {
          employeeName: "李四",
          id: "1212022",
          levelName: "产品经理2"
        },
        {
          employeeName: "王五",
          id: "1312022",
          levelName: "产品经理3"
        },
        {
          employeeName: "赵六",
          id: "1312023",
          levelName: "产品经理3"
        },
        {
          employeeName: "钱七",
          id: "1312024",
          levelName: "产品经理3"
        }
      ];
      return employeeList;
    },

    employeeItemChange(value, item) {
      if (value) {
        if (this.hasSelectionList.find(e => e.id === item.id)) {
          this.$message.warning("此员工已在右侧列表，请重新选择！");
          item.checked = false;
          return;
        }
        this.hasSelectionList.push({
          ...item,
          label: item.employeeName
        });
      } else {
        const index = this.hasSelectionList.findIndex(e => e.id === item.id);
        this.hasSelectionList.splice(index, 1);
      }
    },

    saveAsGroup() {
      const gruopers = [];
      this.hasSelectionList.map(e => {
        gruopers.push(e.label);
      });
      this.gruopForm.gruopers = gruopers.toString();
      this.addGroupVisiable = true;
    },

    confirmAddGruop() {
      this.$refs.gruopForm.validate(valid => {
        if (valid) {
        }
      });
    },

    employeeClick(id) {
      this.employeeActive = id;
    },

    onMove(dir) {
      const moveComm = (curIndex, nextIndex) => {
        const arr = this.hasSelectionList;
        arr[curIndex] = arr.splice(nextIndex, 1, arr[curIndex])[0];
        return arr;
      };
      this.hasSelectionList.some((val, index) => {
        if (val.id === this.employeeActive) {
          if (dir === "up" && index === 0) {
            this.$message.warning("已在顶部！");
          } else if (
            dir === "down" &&
            index === this.hasSelectionList.length - 1
          ) {
            this.$message.warning("已在底部！");
          } else {
            const nextIndex = dir === "up" ? index - 1 : index + 1;
            this.hasSelectionList = moveComm(index, nextIndex);
          }
          return true;
        }
        return false;
      });
    },

    jobItemFun(item) {
      debugger;
      this.jobActive = item.jobCode;
    }
  },

  mounted() {
    this.initAdd();
  }
};
</script>

<template>
  <el-dialog
    v-model="openDialog"
    @closed="handleClose"
    title="请选择岗位"
    width="850px"
  >
    <!-- 保存为组弹窗 -->
    <el-dialog
      v-model="addGroupVisiable"
      width="30%"
      title="保存为组"
      append-to-body
    >
      <el-form
        :model="gruopForm"
        label-width="80px"
        ref="gruopForm"
        :rules="gruopRules"
      >
        <el-form-item label="组名：" style="width: 80%" prop="gruopName">
          <el-input
            v-model="gruopForm.gruopName"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="组员：" style="width: 80%">
          <el-input v-model="gruopForm.gruopers" readonly />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="confirmAddGruop">确定</el-button>
        <el-button @click="addGroupVisiable = false">取消</el-button>
      </template>
    </el-dialog>

    <el-button-group class="ml-10 w-[100%] mb-4">
      <el-button
        type="primary"
        :plain="activeBtn != 'dept'"
        class="w-[10%]"
        @click="switchTreeData('dept')"
        >部门</el-button
      >
      <el-button
        type="primary"
        :plain="activeBtn != 'group'"
        class="w-[10%]"
        @click="switchTreeData('group')"
        >组</el-button
      >
      <el-button
        type="primary"
        :plain="activeBtn != 'job'"
        class="w-[10%]"
        @click="switchTreeData('job')"
        >岗位</el-button
      >
      <el-button
        type="primary"
        :plain="activeBtn != 'level'"
        class="w-[10%]"
        @click="switchTreeData('level')"
        >职级</el-button
      >
    </el-button-group>
    <div class="card-list">
      <!-- 左侧全部 -->
      <el-card class="box-card" :style="{ width: isEmployee ? '70%' : '35%' }">
        <template #header>
          <div class="card-header">
            <div class="header-title">全部</div>
            <el-input v-model="allSearchValue" placeholder="用户名称/用户账号">
              <template #suffix>
                <!-- <img :src="searchIcon" alt="图标" class="icon-size" @click="searchUser('left')" /> -->
                <el-icon class="el-input__icon">
                  <IconifyIconOffline
                    :icon="Search"
                    @click="searchUser('left')"
                  />
                </el-icon>
              </template>
            </el-input>
          </div>
        </template>
        <div style="overflow-y: auto; display: flex">
          <!-- 树状图 -->
          <div
            v-if="activeBtn !== 'job'"
            :style="{ width: isEmployee ? '50%' : '100%' }"
          >
            <el-tree
              :data="treeData"
              :show-checkbox="isMulti && !isEmployee && isMix"
              :props="treeProps"
              node-key="id"
              @check="handleCheckChange"
              ref="treeRef"
              :filter-node-method="filterNode"
              @node-click="handleNodeClick"
              style="padding: var(--el-card-padding)"
            >
              <template #default="{ node, data }">
                <div
                  v-if="!isMulti"
                  :class="[
                    'pl-1',
                    'pr-1',
                    'rounded',
                    'flex',
                    'items-center',
                    'select-none',
                    'w-[100%]',
                    allSearchValue.trim().length > 0 &&
                      node.label.includes(allSearchValue) &&
                      'text-red-500',
                    highlightMap[node.id]?.highlight ? 'dark:text-primary' : ''
                  ]"
                  :style="{
                    background: highlightMap[node.id]?.highlight
                      ? 'var(--el-color-primary-light-7)'
                      : 'transparent'
                  }"
                  style="justify-content: space-between"
                >
                  <div>{{ data.label }}</div>
                  <div v-if="activeBtn === 'group'">{{ data.groupType }}</div>
                </div>
                <span v-else>{{ node.label }}</span>
              </template>
            </el-tree>
          </div>

          <!-- 岗位列表 -->
          <div v-if="activeBtn === 'job'" class="jobsList">
            <div class="jobSubTitle">
              <span>岗位编码</span>
              <span>岗位名称</span>
            </div>
            <div style="padding: var(--el-card-padding) 0px">
              <div
                v-for="(item, index) in jobsList"
                :key="'job_' + index"
                class="jobs-item"
                @click="jobItemFun(item)"
              >
                <div
                  class="jobs-item-content"
                  :class="{ 'jobs-item_active': item.jobCode == jobActive }"
                >
                  <span>{{ item.jobCode }}</span>
                  <span>{{ item.jobName }}</span>
                </div>
              </div>
            </div>
          </div>
          <div
            v-if="isEmployee && activeBtn !== 'job'"
            class="employee-tree-container"
          >
            <!-- <div class="header-title employee-title-bg" style="padding-left: var(--el-card-padding);">人员</div> -->
            <div style="width: 100%">
              <div
                v-for="item in employeeList"
                :key="item.id"
                class="employee-item"
              >
                <div>
                  <el-checkbox
                    v-model="item.checked"
                    :label="item.employeeName"
                    @change="value => employeeItemChange(value, item)"
                  />
                </div>
                <div class="job-item">{{ item.levelName }}</div>
              </div>
            </div>
          </div>
        </div>
        <!-- <div v-if="isEmployee">
          <div class="card-header">
            <div class="header-title employee-title-bg" style="padding-left: var(--el-card-padding);">人员</div>
            <div style="padding: 10px var(--el-card-padding); overflow-y: auto; height: 107px;">
              <div v-for="item in employeeList" :key="item.id" class="employee-item">
                <div>{{ item.employeeName }}</div>
                <div>{{ item.levelName }}</div>
              </div>
            </div>
          </div>
        </div> -->
      </el-card>
      <div class="middle-btn-list">
        <el-button type="primary" circle @click="handleLeftArrow">
          <template #icon>
            <ArrowLeftBold style="width: 10em" />
          </template>
        </el-button>
        <el-button type="primary" circle @click="handleRightArrow">
          <template #icon>
            <ArrowRightBold style="width: 10em" />
          </template>
        </el-button>
      </div>
      <!-- 右侧已选择的 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <div class="header-title" v-if="!isEmployee">
              {{ isMulti ? `已选： ${hasSelectionList.length}` : "单选" }}
            </div>
            <div class="header-title" v-if="isEmployee && !isMulti">单选</div>
            <div class="header-title" v-if="isEmployee && isMulti">
              <el-button link type="primary" @click="saveAsGroup"
                >保存为组</el-button
              >
            </div>
            <el-input v-model="hasSearchValue" placeholder="用户名称/用户账号">
              <template #suffix>
                <!-- <i class="el-icon-search" @click="searchUser('right')"></i> -->
                <el-icon class="el-input__icon">
                  <IconifyIconOffline
                    :icon="Search"
                    @click="searchUser('right')"
                  />
                </el-icon>
              </template>
            </el-input>
          </div>
        </template>
        <div class="tag-list" style="padding: var(--el-card-padding)">
          <div
            v-for="(tag, index) in hasSelectionList"
            class="tag-item"
            :key="tag.id"
            :class="{ 'tag-item_active': tag.id == employeeActive }"
            @click="employeeClick(tag.id)"
          >
            <div class="item-desc">{{ tag.label }}</div>
            <el-button link type="primary" @click="removeUser(tag, index)"
              >删除</el-button
            >
          </div>
        </div>
      </el-card>
      <div class="right_arrow_list" v-if="isMulti && isEmployee">
        <el-button
          type="primary"
          circle
          style="margin: 0 0 8px 12px"
          @click="onMove('up')"
        >
          <template #icon>
            <ArrowUpBold style="width: 10em" />
          </template>
        </el-button>
        <el-button type="primary" circle>
          <template #icon>
            <ArrowDownBold style="width: 10em" @click="onMove('down')" />
          </template>
        </el-button>
      </div>
    </div>

    <template #footer>
      <el-button type="primary" @click="confirmBind">确定</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.card-list {
  display: flex;
  width: 100%;
  justify-content: space-evenly;
  align-items: center;

  .right_arrow_list {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .middle-btn-list {
    display: flex;
    justify-content: center;
    flex-direction: column;
    margin: 0 18px;
    ::v-deep .el-button + .el-button {
      margin-left: 0px;
    }
    .el-button {
      margin-bottom: 8px;
    }
  }

  .box-card {
    width: 35%;
    height: 500px;

    .header-title {
      padding-bottom: 10px;
    }

    :deep(.el-card__body) {
      padding: 0;
    }
    .employee-tree-container {
      padding: var(--el-card-padding);
      overflow-y: auto;
      width: 50%;
      height: 500px;
      border-left: 1px solid var(--el-border-color-light);
    }
    .employee-item {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #606266;
      font-size: var(--el-font-size-base);
      .job-item {
        color: var(--el-text-color-secondary);
      }
    }

    .jobsList {
      display: flex;
      flex-direction: column;
      width: 100%;
      .jobSubTitle {
        background-color: #eeeeee;
        padding: 4px 20px;
        span:first-child {
          padding-right: 30%;
        }
      }
      .jobs-item {
        width: 100%;
        cursor: pointer;
        span:first-child {
          padding-right: 30%;
        }
        .jobs-item-content {
          padding: 4px 20px;
        }
      }
      .jobs-item:hover {
        background: var(--el-fill-color-light);
      }
      .jobs-item_active {
        background: var(--el-fill-color-light);
      }
    }

    .employee-title-bg {
      background-color: #eeeeee;
      padding-top: 10px;
    }

    .tag-list {
      .tag-item {
        display: flex;
        margin-bottom: 6px;
        align-items: center;
        padding: 3px 6px;
        border-radius: 2px;
        cursor: pointer;
        .item-desc {
          width: 90%;
        }
      }
      .tag-item:hover {
        background: var(--el-fill-color-light);
      }
      .tag-item_active {
        background: var(--el-fill-color-light);
      }
    }
  }
}

.icon-size {
  width: 20px;
  height: 20px;
  cursor: pointer;
}
</style>
